﻿using DataPersistence;
using Newtonsoft.Json.Linq;
using NLog;
using QueryDataLogic;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PersistenceDataLogic
{
    public class OperationPrivilege
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        PersistenceData pd = new PersistenceData();
        QueryData qd = new QueryData();
        UserVerify uv = new UserVerify();
        BasicInfo bi = new BasicInfo();

        /// <summary>
        /// 判断模块编码是否存在
        /// </summary>
        /// <returns></returns>
        private bool IsModelNumber(string number, string dbName)
        {
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select id from Model where number = @number"
                };
                comm.Parameters.AddWithValue("@number", number);
                JArray ja = qd.GetData(comm, dbName);

                if (ja.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                logger.Error(ex);
                return false;
            }
        }

        /// <summary>
        /// 判断模块编码是否被权限信息引用
        /// </summary>
        /// <returns></returns>
        private bool IsModelCitePrivilege(int id, string dbName)
        {
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select ID from Privilege where ModelID = @ModelID"
                };
                comm.Parameters.AddWithValue("@ModelID", id);
                JArray ja = qd.GetData(comm, dbName);

                if (ja.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                logger.Error(ex);
                return false;
            }
        }
        
        /// <summary>
        /// 新增、修改、删除模块
        /// </summary>
        /// <returns></returns>
        public JObject OptModel(JObject joParam)
        {
            JObject joResult = new JObject();

            try
            {
                int id = 0;
                //新增时 ID 可以不传
                if (joParam.Property("id") != null)
                {
                    id = (int)joParam["id"];
                }
                string state = (string)joParam["state"];
                string name = (string)joParam["name"];
                string number = (string)joParam["number"];
                string Url = (string)joParam["url"];
                string Remark = "";
                if (joParam.Property("remark") != null)
                {
                    Remark = (string)joParam["remark"];
                }
                
                int resultLine = 0;
                SqlCommand comm = new SqlCommand();
                if (state == "add")
                {
                    if (!IsModelNumber(number, "MealManage"))
                    {
                        comm.CommandText = "INSERT INTO Model(number,name,Url,Remark) VALUES(@number,@name,@Url,@Remark)";

                        comm.Parameters.AddWithValue("@name", name);
                        comm.Parameters.AddWithValue("@number", number);
                        comm.Parameters.AddWithValue("@Url", Url);
                        comm.Parameters.AddWithValue("@Remark", Remark);

                        resultLine = pd.ExeSqlCode(comm, "MealManage");

                        if (resultLine > 0)
                        {
                            joResult["message"] = "添加模块 " + number + " 成功";
                            joResult["data"] = resultLine;
                            joResult["state"] = true;
                        }
                        else
                        {
                            joResult["message"] = "添加模块 " + number + " 失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    }
                    else
                    {
                        joResult["data"] = 0;
                        joResult["message"] = "模块编码已经存在，请重新添加";
                        joResult["state"] = false;
                        return joResult;
                    }
                }
                else if (state == "modify")
                {
                    //if (!IsModelNumber(number, "MealManage"))
                    //{
                        comm.CommandText = "UPDATE Model SET name = @name,url = @url,remark=@remark WHERE id = @id ";

                        comm.Parameters.AddWithValue("@id", id);
                        comm.Parameters.AddWithValue("@name", name);
                        comm.Parameters.AddWithValue("@number", number);
                        comm.Parameters.AddWithValue("@url", Url);
                        comm.Parameters.AddWithValue("@remark", Remark);

                        resultLine = pd.ExeSqlCode(comm, "MealManage");

                        if (resultLine > 0)
                        {
                            joResult["message"] = "修改模块 " + number + " 成功";
                            joResult["data"] = resultLine;
                            joResult["state"] = true;
                        }
                        else
                        {
                            joResult["message"] = "修改模块 " + number + " 失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    //}
                    //else
                    //{
                    //    joResult["data"] = 0;
                    //    joResult["message"] = "模块编码已经存在，修改失败";
                    //    joResult["state"] = false;
                    //    return joResult;
                    //}
                }
                else if (state == "del")
                {
                    if (!IsModelCitePrivilege(id, "MealManage"))
                    {
                        comm.CommandText = "DELETE FROM Model WHERE id = @id ";

                        comm.Parameters.AddWithValue("@id", id);

                        resultLine = pd.ExeSqlCode(comm, "MealManage");

                        if (resultLine > 0)
                        {
                            joResult["message"] = "删除模块 " + number + " 成功";
                            joResult["data"] = resultLine;
                            joResult["state"] = true;
                        }
                        else
                        {
                            joResult["message"] = "删除模块 " + number + " 失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    }
                    else
                    {
                        joResult["message"] = "模块“" + name + "”被权限信息引用，无法删除";
                        joResult["data"] = resultLine;
                        joResult["state"] = false;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }

            return joResult;
        }

        /// <summary>
        /// 判断权限编码是否存在
        /// </summary>
        /// <returns></returns>
        private bool IsPrivilegeNumber(string number, string dbName)
        {
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select id from Privilege where number = @number"
                };
                comm.Parameters.AddWithValue("@number", number);
                JArray ja = qd.GetData(comm, dbName);

                if (ja.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                logger.Error(ex);
                return false;
            }
        }

        /// <summary>
        /// 判断权限编码是否被授权
        /// </summary>
        /// <returns></returns>
        private bool IsPrivilegeCiteRolePrivilege(int id, string dbName)
        {
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select ID from RolePrivilege where PrivilegeID = @PrivilegeID"
                };
                comm.Parameters.AddWithValue("@PrivilegeID", id);
                JArray ja = qd.GetData(comm, dbName);

                if (ja.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                logger.Error(ex);
                return false;
            }
        }

        /// <summary>
        /// 新增、修改、删除权限
        /// </summary>
        /// <returns></returns>
        public JObject OptPrivilege(JObject joParam)
        {
            JObject joResult = new JObject();

            try
            {
                int id = 0;
                //新增时 ID 可以不传
                if (joParam.Property("id") != null)
                {
                    id = (int)joParam["id"];
                }
                string state = (string)joParam["state"];
                string name = (string)joParam["name"];
                string number = (string)joParam["number"];
                int ModelID = (int)joParam["modelID"];
                string Remark = "";
                if (joParam.Property("remark") != null)
                {
                    Remark = (string)joParam["remark"];
                }

                int resultLine = 0;
                SqlCommand comm = new SqlCommand();
                if (state == "add")
                {
                    if (!IsPrivilegeNumber(number, "MealManage"))
                    {
                        comm.CommandText = "INSERT INTO Privilege(number,name,ModelID,Remark) VALUES(@number,@name,@ModelID,@Remark)";

                        comm.Parameters.AddWithValue("@name", name);
                        comm.Parameters.AddWithValue("@number", number);
                        comm.Parameters.AddWithValue("@ModelID", ModelID);
                        comm.Parameters.AddWithValue("@Remark", Remark);

                        resultLine = pd.ExeSqlCode(comm, "MealManage");

                        if (resultLine > 0)
                        {
                            joResult["message"] = "添加权限 " + number + " 成功";
                            joResult["data"] = resultLine;
                            joResult["state"] = true;
                        }
                        else
                        {
                            joResult["message"] = "添加权限 " + number + " 失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    }
                    else
                    {
                        joResult["data"] = 0;
                        joResult["message"] = "权限编码已经存在，请重新添加";
                        joResult["state"] = false;
                        return joResult;
                    }
                }
                else if (state == "modify")
                {
                    //if (!IsPrivilegeNumber(number, "MealManage"))
                    //{
                        comm.CommandText = "UPDATE Privilege SET name = @name,ModelID = @ModelID,remark=@remark WHERE id = @id ";

                        comm.Parameters.AddWithValue("@id", id);
                        comm.Parameters.AddWithValue("@name", name);
                        comm.Parameters.AddWithValue("@number", number);
                        comm.Parameters.AddWithValue("@ModelID", ModelID);
                        comm.Parameters.AddWithValue("@remark", Remark);

                        resultLine = pd.ExeSqlCode(comm, "MealManage");

                        if (resultLine > 0)
                        {
                            joResult["message"] = "修改权限 " + number + " 成功";
                            joResult["data"] = resultLine;
                            joResult["state"] = true;
                        }
                        else
                        {
                            joResult["message"] = "修改权限 " + number + " 失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    //}
                    //else
                    //{
                    //    joResult["data"] = 0;
                    //    joResult["message"] = "权限编码已经存在，修改失败";
                    //    joResult["state"] = false;
                    //    return joResult;
                    //}
                }
                else if (state == "del")
                {
                    if (!IsPrivilegeCiteRolePrivilege(id, "MealManage"))
                    {
                        comm.CommandText = "DELETE FROM Privilege WHERE id = @id ";

                        comm.Parameters.AddWithValue("@id", id);

                        resultLine = pd.ExeSqlCode(comm, "MealManage");

                        if (resultLine > 0)
                        {
                            joResult["message"] = "删除权限 " + number + " 成功";
                            joResult["data"] = resultLine;
                            joResult["state"] = true;
                        }
                        else
                        {
                            joResult["message"] = "删除权限 " + number + " 失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    }
                    else
                    {
                        joResult["message"] = "权限“" + name + "”已被授权，无法删除";
                        joResult["data"] = resultLine;
                        joResult["state"] = false;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }

            return joResult;
        }

        /// <summary>
        /// 判断角色编码是否存在
        /// </summary>
        /// <returns></returns>
        private bool IsRoleNumber(string number, string dbName)
        {
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select id from Role where number = @number"
                };
                comm.Parameters.AddWithValue("@number", number);
                JArray ja = qd.GetData(comm, dbName);

                if (ja.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                logger.Error(ex);
                return false;
            }
        }

        /// <summary>
        /// 判断角色编码是否被授权
        /// </summary>
        /// <returns></returns>
        private bool IsRoleCiteUserRole(int id, string dbName)
        {
            try
            {
                //获取所有的公司信息 循环遍历 查询角色是否被授权
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select ID,Number,Name,DatabaseName from Company "
                };

                JArray ja = qd.GetData(comm, dbName);
                JArray jaUserRole = new JArray();
                JObject joCompany = new JObject();
                if (ja.Count > 0)
                {
                    for (int jaIndex = 0; jaIndex < ja.Count; jaIndex++)
                    {
                        joCompany = (JObject)ja[jaIndex];
                        comm = new SqlCommand()
                        {
                            CommandText = "select ID from UserRole where RoleID = @RoleID"
                        };
                        comm.Parameters.AddWithValue("@RoleID", id);
                        jaUserRole = new JArray();
                        jaUserRole = qd.GetData(comm, (string)joCompany["DatabaseName"]);

                        if (ja.Count > 0)
                        {
                            return true;
                        }
                    }
                }
                else
                {
                    return false;
                }
                return false;
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                logger.Error(ex);
                return false;
            }
        }

        /// <summary>
        /// 新增、修改、删除角色
        /// </summary>
        /// <returns></returns>
        public JObject OptRole(JObject joParam)
        {
            JObject joResult = new JObject();

            try
            {
                int id = 0;
                //新增时 ID 可以不传
                if (joParam.Property("id") != null)
                {
                    id = (int)joParam["id"];
                }
                string state = (string)joParam["state"];
                string name = (string)joParam["name"];
                string number = (string)joParam["number"];
                string Remark = "";
                if (joParam.Property("remark") != null)
                {
                    Remark = (string)joParam["remark"];
                }

                int resultLine = 0;
                SqlCommand comm = new SqlCommand();
                if (state == "add")
                {
                    if (!IsPrivilegeNumber(number, "MealManage"))
                    {
                        comm.CommandText = "INSERT INTO Role(number,name,Remark) VALUES(@number,@name,@Remark)";

                        comm.Parameters.AddWithValue("@name", name);
                        comm.Parameters.AddWithValue("@number", number);
                        comm.Parameters.AddWithValue("@Remark", Remark);

                        resultLine = pd.ExeSqlCode(comm, "MealManage");

                        if (resultLine > 0)
                        {
                            joResult["message"] = "添加角色 " + number + " 成功";
                            joResult["data"] = resultLine;
                            joResult["state"] = true;
                        }
                        else
                        {
                            joResult["message"] = "添加角色 " + number + " 失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    }
                    else
                    {
                        joResult["data"] = 0;
                        joResult["message"] = "角色编码已经存在，请重新添加";
                        joResult["state"] = false;
                        return joResult;
                    }
                }
                else if (state == "modify")
                {
                    //if (!IsPrivilegeNumber(number, "MealManage"))
                    //{
                        comm.CommandText = "UPDATE Role SET name = @name,remark=@remark WHERE id = @id ";

                        comm.Parameters.AddWithValue("@id", id);
                        comm.Parameters.AddWithValue("@name", name);
                        comm.Parameters.AddWithValue("@number", number);
                        comm.Parameters.AddWithValue("@remark", Remark);

                        resultLine = pd.ExeSqlCode(comm, "MealManage");

                        if (resultLine > 0)
                        {
                            joResult["message"] = "修改角色 " + number + " 成功";
                            joResult["data"] = resultLine;
                            joResult["state"] = true;
                        }
                        else
                        {
                            joResult["message"] = "修改角色 " + number + " 失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    //}
                    //else
                    //{
                    //    joResult["data"] = 0;
                    //    joResult["message"] = "角色编码已经存在，修改失败";
                    //    joResult["state"] = false;
                    //    return joResult;
                    //}
                }
                else if (state == "del")
                {
                    if (!IsRoleCiteUserRole(id, "MealManage"))
                    {
                        comm.CommandText = "DELETE FROM Role WHERE id = @id ";

                        comm.Parameters.AddWithValue("@id", id);

                        resultLine = pd.ExeSqlCode(comm, "MealManage");

                        if (resultLine > 0)
                        {
                            joResult["message"] = "删除角色 " + number + " 成功";
                            joResult["data"] = resultLine;
                            joResult["state"] = true;
                        }
                        else
                        {
                            joResult["message"] = "删除角色 " + number + " 失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    }
                    else
                    {
                        joResult["message"] = "角色“" + name + "”已被授权，无法删除";
                        joResult["data"] = resultLine;
                        joResult["state"] = false;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }

            return joResult;
        }
    }
}
